package day01;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 若雨成霜
 */
public class Day01_2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        String num1 = reversalNum(l1), num2 = reversalNum(l2);
        int size1 = num1.length(), size2 = num2.length();
        List<Integer> result = new ArrayList<>();
        int tempValue = 0;
        if (size1 == size2) {
            for (int i = 0; i < size1; i++) {
                int temp1 = getSingleNum(num1, i);
                int temp2 = getSingleNum(num2, i);
                tempValue = getIncreaseNum(temp1, temp2, tempValue, result);
            }
        } else {
            String maxNum = size1 > size2 ? num1 : num2;
            String minNum = size1 > size2 ? num2 : num1;
            for (int i = 0, j = maxNum.length(); i < j; i++) {
                int temp1 = getSingleNum(maxNum, i);
                int temp2 = getSingleNum(minNum, i);
                tempValue = getIncreaseNum(temp1, temp2, tempValue, result);
            }
        }
        return toNode(result);
    }

    private int getIncreaseNum(int source, int target, int carry, List<Integer> result) {
        int sumValue = source + target + carry;
        int increaseNum = sumValue / 10;
        int realValue = sumValue % 10;
        result.add(realValue);
        return increaseNum;
    }

    private int getSingleNum(String content, int index) {
        if (index > content.length() - 1) {
            return 0;
        }
        return Integer.parseInt(String.valueOf(content.charAt(index)));
    }

    public String reversalNum(ListNode node) {
        List<String> value = new ArrayList<>();
        explain(node, value);
        StringBuilder builder = new StringBuilder();
        for (int i = value.size() - 1; i >= 0; i--) {
            builder.append(value.get(i));
        }
        return builder.toString();
    }

    public void explain(ListNode node, List<String> value) {
        value.add(String.valueOf(node.val));
        if (node.next != null) {
            explain(node.next, value);
        }
    }
}
